// Yang Shuai  Copyright (c) 2022 https://yby6.com.
// Copyright (c) 2022. Yangbuyi, personal projects are not allowed to be commercialized without permission.
// Please keep the information of the original author of the code. Thank you
//

package com.leetroll.app.controller;

import com.leetroll.app.service.SmsService;
import com.leetroll.app.utils.MailUtil;
import com.leetroll.app.utils.PhoneUtils;
import com.leetroll.common.bean.ApiResponse;
import com.leetroll.common.exception.BusinessException;
import com.leetroll.common.utils.ResultUtil;
import com.leetroll.common.utils.StringUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
public class SmsController {

    private final StringRedisTemplate redisTemplate;
    private final SmsService smsService;

    @Autowired
    public SmsController(StringRedisTemplate redisTemplate, SmsService smsService) {
        this.redisTemplate = redisTemplate;
        this.smsService = smsService;
    }

    /**
     * 根据手机号码发送验证码
     * 阿里云短信验证码
     */
    @ApiOperation(value = "发送手机验证码")
    @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String")
    @GetMapping(value = "/send/{phone}")
    public ApiResponse<String> send(@PathVariable String phone) {
        // 校验手机号是否合法
        if (!PhoneUtils.isPhone(phone)) {
            throw new BusinessException("手机号码格式出错请重新输入!");
        }
        // 查看redis当中是否有当前手机对应的验证码   手机号当作key
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            //已经发送过了 还没有过期
            return ApiResponse.OK("消息已发送");
        }
        // 生成新的验证码
        code = randomCode();
        Map<String, Object> param = new HashMap<>();
        //把验证码写到参数当中
        param.put("code", code);
        System.out.println("code: " + code);
        //发送短信
//        boolean isSend = smsService.send(phone, param);
        //发送成功
        return getResponseResult(phone, code, true);
    }


    /**
     * 发送腾讯云短信
     */
    @GetMapping(value = "/send/tencentSms/{phone}")
    public ApiResponse<String> tencentSms(@PathVariable String phone) {
        // 校验手机号是否合法
        if (!PhoneUtils.isPhone(phone)) {
            throw new BusinessException("手机号码格式出错请重新输入!");
        }
        // 查看redis当中是否有当前手机对应的验证码   手机号当作key
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            //已经发送过了 还没有过期
            return ApiResponse.OK("消息已发送");
        }
        // 生成新的验证码
        code = randomCode();
        //发送短信
        boolean isSend = smsService.sendTencentSms(code, phone);
        return getResponseResult(phone, code, isSend);
    }

    /**
     * 发送邮箱登录信息
     * 参数： to : 接收者邮箱
     * subject: 主题
     * remark: 备注
     */
    @PostMapping(value = "/send/mail")
    public String sendMail(@RequestBody Map<String, Object> map) {
        String to = map.get("to").toString();
        String subject = map.get("subject").toString();
        String userName = map.get("userName").toString();
        boolean flag = MailUtil.sendEmail(to, subject, userName, true, "", "博客地址: https://www.yangbuyi.top");
        //发送成功
        if (flag) {
            return ResultUtil.successWithMessage("发送成功！");
        } else {
            //提示用户失败
            return ResultUtil.errorWithMessage("发送邮件失败");
        }
    }


    /**
     * 短信发送返回响应
     *
     * @param phone  手机号码
     * @param code   验证码
     * @param isSend 是否发送成功
     */
    private ApiResponse<String> getResponseResult(@PathVariable String phone, String code, boolean isSend) {
        //发送成功
        if (isSend) {
            //把验证码写到redis当中 五分钟过期时间
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return ApiResponse.OK("发送成功！");
        } else {
            //提示用户失败
            return ApiResponse.FAIL("发送短信失败");
        }
    }

    /**
     * 生成4位的数字验证码
     */
    private String randomCode() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int s = new Random().nextInt(10);
            sb.append(s);
        }
        return sb.toString();
    }
}